<?php

class task_model extends Model
{
    function getCategories(): ?array
    {
        $data = $this->db->select('tb_category', array('id', 'name', 'variable'));
        if(empty($data)){
            $data = [];
        }
        return $data;
    }

    function list($where, $pagination): array
    {
        if (!is_array($where)) {
            $where = [];
        }
        //page limit
        $where["del"] = 0;
        $orderby = 'zhiding DESC, status, create_time DESC';
        $data = $this->db->select('tb_task', ["id", "content", "status", "urgent", "create_time", "update_time", "category", "zhiding", "sort"], $where, $orderby, $pagination);
        if (empty($data)) {
            $data = [];
        }

        $categories = $this->getCategories();
        $temp = [];
        foreach ($categories as $category) {
            $temp[$category['id']]=$category;
        }
        $tempData = [];
        foreach ($data as $item){
            if(!empty($item['category'])){
                $item['categoryId'] = $item['category'];
                $item['category_n'] = $temp[$item['category']]['name'];
            }
            $tempData[]=$item;
        }
        $data = $tempData;

        $csql = "SELECT COUNT(id) AS total FROM `tb_task` WHERE";
        if (is_array($where)) {
            foreach ($where as $k => $v) {
                if ($k == "update_time") {
                    $k = "DATE_FORMAT(update_time, '%Y-%m-%d')";
                    $v = date('Y-m-d', $v);
                }
                $csql = $csql . " " . $k . "='" . $v . "' and";
            }
            $csql = substr($csql, 0, -3);
        }
        $cresult = $this->db->query_sql($csql);
        $crow = $cresult->fetch_assoc();
        $total_rows = $crow["total"];
        return array("list" => $data, "total" => $total_rows);
    }

    function add($task)
    {
        return $this->db->insert('tb_task', $task);
    }

    function edit($task, $where)
    {
        return $this->db->update('tb_task', $task, $where);
    }

    function chartView($datetime, $dataKeyType, $chartKeyType): array
    {
        //数据展示
        // 查询当天、一周内、一月内总完成任务数（根据传的key指定[day, week, month]）
        // 查询当前剩余未完成任务数
        $_format = 'Y-m-d';
        $today = $datetime;
        //日
        $weekInterval = new DateInterval('P1W');
        $monthInterval = new DateInterval('P1M');
        //周
        $todayDate = new DateTime($datetime);
        $preWeekDate = $todayDate->sub($weekInterval);
        $preWeekDate->add(new DateInterval('P1D'));
        $pre_weekday = $preWeekDate->format($_format);
        //月
        $todayDate = new DateTime($datetime);
        $preMonthDate = $todayDate->sub($monthInterval);
        $preMonthDate->add(new DateInterval('P1D'));
        $pre_monthday = $preMonthDate->format($_format);

        $panel = array();//返回体，面板数据
        $finished_count = 0;
        $unfinished_count = 0;
        $_finish='';

        //完成->最后更新时间是今天并且完成状态
        //未完成->所有未完成
        if($dataKeyType === 'day'){
            //当天查
            $_finish = "select count(*) as count from tb_task where date_format(update_time, '%Y-%m-%d')='{$today}' and del=0 and status=1;";
        }elseif($dataKeyType === 'week'){
            //当周查
            $_finish = "select count(*) as count from tb_task where date_format(update_time, '%Y-%m-%d') between '{$pre_weekday}' and '{$today}' and del=0 and status=1;";
        }elseif($dataKeyType == 'month'){
            //当月查
            $_finish = "select count(*) as count from tb_task where date_format(update_time, '%Y-%m-%d') between '{$pre_monthday}' and '{$today}' and del=0 and status=1;";
        }

        $finish_result = $this->db->query_sql($_finish);
        $rows = $finish_result->fetch_assoc();
        if(!empty($rows)){
            $finished_count = $rows['count'];
        }

        $_unfinished = "select count(*) as count from tb_task where del=0 and status=0;";
        $unfinished_result = $this->db->query_sql($_unfinished);
        $task_unfinished = $unfinished_result->fetch_assoc();
        if(!empty($task_unfinished)){
            $unfinished_count = $task_unfinished['count'];
        }
        $panel['finished']=$finished_count;
        $panel['unfinished']=$unfinished_count;


        $chart = [];//返回体
        $pre_date='';//过去时间
        $pre_dates=[];//过去时间列表
        //图表展示
        //默认查询一周内每日完成任务数和新增任务数
        if($chartKeyType == 'week'){
            $preWeekDate = new DateTime($pre_weekday);
            for ($i = 0; $i < 7; $i++) {
                $pre_dates[] = $preWeekDate->format($_format);
                $preWeekDate->add(new DateInterval('P1D'));
            }
            $pre_date=$pre_weekday;
        }else{
            //查一月 日期分组查完成任务数
            $preMonthDate = new DateTime($pre_monthday);
            for ($i = 0; $i < 30; $i++) {
                $pre_dates[] = $preMonthDate->format($_format);
                $preMonthDate->add(new DateInterval('P1D'));
                if($preMonthDate > new DateTime()){
                    break;
                }
            }
            $pre_date=$pre_monthday;
        }
        $_pre_finish = "select date_format(update_time, '%Y-%m-%d') as date, count(*) as count from tb_task where del=0 and status=1 and date_format(update_time, '%Y-%m-%d') between '{$pre_date}' and '{$today}' group by date_format(update_time, '%Y-%m-%d')";
        $_pre_create = "select date_format(create_time, '%Y-%m-%d') as date, count(*) as count from tb_task where del=0 and date_format(create_time, '%Y-%m-%d') between '{$pre_date}' and '{$today}' group by date_format(create_time, '%Y-%m-%d')";
        //日期分组查完成任务数
        $finish_result_rows = $this->db->query_sql($_pre_finish);
        $rows_finish = $finish_result_rows->fetch_all();
        //日期分组查创建任务数
        $create_result_rows = $this->db->query_sql($_pre_create);
        $rows_create = $create_result_rows->fetch_all();
        $chart['cols'] = $pre_dates;
        foreach ($pre_dates as $v){
            $week_date_finished=0;
            $week_date_create=0;
            if(!empty($rows_finish) && is_array($rows_finish)){
                foreach ($rows_finish as $sub_v){
                    if($sub_v[0] == $v){
                        $week_date_finished = $sub_v[1];
                    }
                }
            }
            if(!empty($rows_create) && is_array($rows_create)){
                foreach ($rows_create as $sub_v){
                    if($sub_v[0] == $v){
                        $week_date_create = $sub_v[1];
                    }
                }
            }
//            $chart[$v]=array('finished'=> $week_date_finished, 'create'=> $week_date_create);
            $chart['dataset'][]=array('finished'=> $week_date_finished, 'create'=> $week_date_create);
        }

        return array("panel" => $panel, "chart" => $chart);
    }
}
